const md5 = require('../../utils/md5.js');
  // ... existing code ...
Page({
  data: {
    activities: [],
    location: '',
    showHotSection: false,
    remote_src: getApp().globalData.remote_src,
    currentTimeFilter: 'week',
    currentTypeFilter: 'all',
    typeMap: {
      'all': '全部',
      'photo': '拍照',
      'travel': '旅行',
      'food': '美食',
      'sports': '运动',
      'movie': '电影',
      'study': '学习',
      'outdoor': '户外',
      'others': '其他'
    },
    searchKeyword: '',
    hotRanks: [],
    currentWeek: '',
    showFilterModal: false,
     // 筛选条件
    filterType: 'all',
    filterArea: 'all', 
    filterPeople: 'all',
    // 原始活动数据（用于重置筛选）
    originalActivities: [],
  },
  // 类型筛选
  filterByType(e) {
    const type = e.currentTarget.dataset.type;
    this.setData({
      filterType: type
    });
  },
  
  // 区域筛选
  filterByArea(e) {
    const area = e.currentTarget.dataset.area;
    this.setData({
      filterArea: area
    });
  },
  
  // 人数筛选
  filterByPeople(e) {
    const people = e.currentTarget.dataset.people;
    this.setData({
      filterPeople: people
    });
  },
   
  // 重置筛选
  resetFilter() {
    this.setData({
      filterType: 'all',
      filterArea: 'all',
      filterPeople: 'all'
    });
    wx.showToast({
      title: '已重置筛选条件',
      icon: 'success',
      duration: 1000
    });
  },
  
  // 确认筛选
  confirmFilter() {
    // 应用筛选条件
    this.applyFilters();
    // 关闭筛选弹窗
    this.setData({
      showFilterModal: false
    });
    wx.showToast({
      title: '已筛选',
      icon: 'success',
      duration: 1000
    });
  },
    // 应用筛选条件
  applyFilters() {
    let filteredActivities = [...this.data.originalActivities];
    
    // 类型筛选
    if (this.data.filterType !== 'all') {
      filteredActivities = filteredActivities.filter(activity => {
        return activity.type === this.data.filterType;
      });
    }
    
    // 区域筛选
    if (this.data.filterArea !== 'all') {
      filteredActivities = filteredActivities.filter(activity => {
        return activity.address && activity.address.name && 
               activity.address.name.includes(this.data.filterArea);
      });
    }
    
    // 人数筛选
    if (this.data.filterPeople !== 'all') {
      filteredActivities = filteredActivities.filter(activity => {
        const peopleCount = parseInt(activity.people_number) || 0;
        switch(this.data.filterPeople) {
          case '1-3人':
            return peopleCount >= 1 && peopleCount <= 3;
          case '3-5人':
            return peopleCount > 3 && peopleCount <= 5;
          case '5-10人':
            return peopleCount > 5 && peopleCount <= 10;
          default:
            return true;
        }
      });
    }
    
    this.setData({
      activities: filteredActivities
    });
  },
   // 显示筛选弹窗
  showFilterModal() {
    this.setData({
      showFilterModal: true
    });
  },
  
  // 隐藏筛选弹窗
  closeFilterModal() {
    this.setData({
      showFilterModal: false
    });
  },
  
  // 阻止事件冒泡
  stopPropagation() {
    // 空函数，阻止点击内容区域时关闭弹窗
  },
  // 搜索框输入事件
  onSearchInput(e) {
    this.setData({
      searchKeyword: e.detail.value
    });
  },
  getCurrentQueryOptions() {
    // 基础查询参数
    const baseOptions = {
      status: '0',  // 未成团的活动
      page: 1,
      page_size: 20,
      city: this.data.location || '深圳'
    };

    // 处理活动类型
    if (this.data.currentTypeFilter !== 'all') {
      baseOptions.type = this.data.typeMap[this.data.currentTypeFilter];
    }
    // 处理搜索关键字
    if (this.data.searchKeyword) {
      baseOptions.keyword = this.data.searchKeyword;
    }
    // 处理时间筛选
    const now = new Date();
    if (this.data.currentTimeFilter === 'nearby') {
        wx.getLocation({
          type: 'gcj02',
          success: (res) => {
            baseOptions.latitude = res.latitude;
            baseOptions.longitude = res.longitude;
            baseOptions.distance = 10;
          },
          fail: () => {
            wx.showToast({
              title: '获取位置失败',
              icon: 'none'
            });
          }
        });
    }
    
    if (this.data.currentTimeFilter === 'week') {
      // 本周活动
      const currentDay = now.getDay() || 7;
      const monday = new Date(now);
      monday.setDate(now.getDate() - currentDay + 1);
      monday.setHours(0, 0, 0, 0);
      
      const sunday = new Date(monday);
      sunday.setDate(monday.getDate() + 6);
      sunday.setHours(23, 59, 59, 999);
      
      baseOptions.start_date = this.formatDate(monday) + " 00:00:00";
      baseOptions.end_date = this.formatDate(sunday) + " 23:59:59";

    } else if (this.data.currentTimeFilter === 'weekend') {
      // 周末活动
      const saturday = new Date(now);
      saturday.setDate(now.getDate() + (6 - now.getDay()));
      saturday.setHours(0, 0, 0, 0);
      
      const sunday = new Date(saturday);
      sunday.setDate(saturday.getDate() + 1);
      sunday.setHours(23, 59, 59, 999);
      
      baseOptions.start_date = this.formatDate(saturday);
      baseOptions.end_date = this.formatDate(sunday);

    } else if (this.data.currentTimeFilter === 'workday') {
      // 工作日活动
      const currentDay = now.getDay();
      const monday = new Date(now);
      monday.setDate(now.getDate() - currentDay + 1);
      monday.setHours(0, 0, 0, 0);
      
      const friday = new Date(monday);
      friday.setDate(monday.getDate() + 4);
      friday.setHours(23, 59, 59, 999);
      
      baseOptions.start_date = this.formatDate(monday);
      baseOptions.end_date = this.formatDate(friday);
    }

    return baseOptions;
  },
  // 搜索确认事件
  onSearch() {
    const options = this.getCurrentQueryOptions();
    console.log('搜索确认', options);
    this.getActivities(options);
  },
  switchTypeFilter(e) {
    const type = e.currentTarget.dataset.type;
    console.log('切换活动类型', type);
    this.setData({
      currentTypeFilter: type
    });
    const options = this.getCurrentQueryOptions();
    this.getActivities(options);
  },
  switchTimeFilter(e) {
    const type = e.currentTarget.dataset.type;
    this.setData({
      currentTimeFilter: type
    });
    console.log('切换时间筛选', type);
    const options = this.getCurrentQueryOptions();
    this.getActivities(options);
  },
  checkCityAndUpdateUI(cityName) {
    const hotCities = ['北京', '上海', '广州', '深圳', '杭州'];
    const showHot = hotCities.some(city => cityName.includes(city));
    this.setData({
      showHotSection: showHot
    });
  },
  chooseLocation() {
    // 先检查权限状态
    wx.getSetting({
      success: (res) => {
        if (!res.authSetting['scope.userLocation']) {
          // 如果没有权限，先申请权限
          wx.authorize({
            scope: 'scope.userLocation',
            success: () => {
              this.getLocationAndChoose();
            },
            fail: () => {
              // 用户拒绝授权，引导打开设置页
              wx.showModal({
                title: '需要位置权限',
                content: '请授权位置信息以便选择活动地点',
                confirmText: '去设置',
                success: (res) => {
                  if (res.confirm) {
                    wx.openSetting();
                  }
                }
              });
            }
          });
        } else {
          // 已有权限，直接获取位置
          console.log('已授权位置信息');
          this.getLocationAndChoose();
        }
      }
    });
  },
  getLocationAndChoose() {
    wx.getLocation({
      type: 'gcj02',
      success: (res) => {
        wx.chooseLocation({
          latitude: res.latitude,
          longitude: res.longitude,
          success: (res) => {
            console.log('选择地点', res);
            const cityMatch = res.address.match(/([^省]+市)/);
            let cityName = '';
            if (cityMatch) {
              cityName = cityMatch[1];
            } 
            this.setData({ location: cityName });
            getApp().globalData.location = cityName; // 更新全局位置
            this.checkCityAndUpdateUI(cityName);
          }
        });
      }
    });
  },
  getInitLocation() {
    console.log('获取初始位置');
    wx.getLocation({
      type: 'gcj02',
      success: (res) => {
        const key = 'B4FBZ-IIEL5-KTGID-IE5RU-GPV7F-GLFSR';
        const sk = 'yjrbsceakcquwSFHkwvCOJql9eDzuOSb';  // 填入你的腾讯地图密钥
        const location = `${res.latitude},${res.longitude}`;
        const timestamp = Math.floor(Date.now() / 1000);
        
        // 计算签名
        const params = {
          location,
          key,
          timestamp
        };
        const signStr = Object.keys(params)
          .sort()
          .map(key => `${key}=${params[key]}`)
          .join('&');
        const sig = md5(`/ws/geocoder/v1/?${signStr}${sk}`);

        wx.request({
          url: `https://apis.map.qq.com/ws/geocoder/v1/`,
          data: {
            ...params,
            sig
          },
          success: (result) => {
            console.log('获取位置信息成功', result);
            if (result.data.status === 0) {
              const locationName = result.data.result.address_component.city;
              this.setData({ location: locationName });
              getApp().globalData.location = locationName;
              this.checkCityAndUpdateUI(locationName);
            }
          },
          fail: (err) => {
            console.error('获取位置信息失败', err); 
          }
        });
      }
    });
  },
  onLoad() {
     // 先检查权限
     wx.getSetting({
      success: (res) => {
        if (res.authSetting['scope.userLocation']) {
          this.getInitLocation();
        } else {
          this.setData({ location: '深圳' });
          this.checkCityAndUpdateUI('深圳');
        }
      }
    });
  },
  onShow() {
   
    const options = this.getCurrentQueryOptions();
    this.getActivities(options);
    this.loadActivityTypeFavStats();
  },
   // 添加新方法：获取活动类型收藏统计
  loadActivityTypeFavStats() {
    const websiteUrl = getApp().globalData.onlineService + '/api/activity/activity_type';
    wx.request({
      url: websiteUrl,
      method: 'GET',
      header: {
        'content-type': 'application/json',
        'Authorization': `Bearer ${getApp().globalData.userInfo.token}`
      },
      data: {
        city: this.data.location || '深圳'
      },
      success: (res) => {
        if (res.data.code === 200) {
          const cityStats = res.data.data;
          console.log('活动类型统计', cityStats);
          // 将统计数据转换为排序后的数组
          const rankList = Object.entries(cityStats)
            .map(([type, count]) => ({
              type,
              count
            }))
            .sort((a, b) => b.count - a.count)
            .slice(0, 3);  // 只取前三名

          this.setData({
            showHotSection: true,
            hotRanks: rankList
          });
        }
      },
      fail: () => {
        console.error('获取活动类型统计失败');
        this.setData({
          showHotSection: false
        });
      }
    });
     // 设置当前周信息
     const now = new Date();
     const currentDay = now.getDay() || 7;
     const monday = new Date(now);
     monday.setDate(now.getDate() - currentDay + 1);
     
     const sunday = new Date(monday);
     sunday.setDate(monday.getDate() + 6);
     
     const weekNumber = Math.ceil((now.getDate() - currentDay + 1) / 7);
     const formatDate = (date) => {
       const month = String(date.getMonth() + 1).padStart(2, '0');
       const day = String(date.getDate()).padStart(2, '0');
       return `${month}.${day}`;
     };
     
     this.setData({
       currentWeek: `第${weekNumber}周 | ${formatDate(monday)}-${formatDate(sunday)}`
     });
  },
  getActivities(options) {
    const websiteUrl = getApp().globalData.onlineService + '/api/activity/activity'; 
    console.log('请求参数', options);
    wx.request({
      url: websiteUrl,
      method: 'GET',
      header: {
        'content-type': 'application/json',
        'Authorization': `Bearer ${getApp().globalData.userInfo.token}`
      },
      data: options,
      success: (res) => {
        console.log('获取活动成功', res);
        if (res.data.code === 200) {
          this.setData({
            activities: res.data.data.activities,
            originalActivities: res.data.data.activities, // 保存原始数据
          });
        } else {
          wx.showToast({
            title: res.data.msg || '获取活动失败',
            icon: 'none'
          });
        }
      },
      fail: (err) => {
        wx.showToast({
          title: '网络请求失败',
          icon: 'none'
        });
      }
    });
  },
  // 跳转到活动详情页
  navigateToDetail(e) {
    const { id } = e.currentTarget.dataset;
    wx.navigateTo({
      url: `/pages/home/activity/activity?id=${id}`,
      fail: (err) => {
        wx.showToast({
          title: '页面跳转失败',
          icon: 'none'
        });
      }
    });
  },
  // 日期格式化辅助函数
  formatDate(date) {
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    return `${year}-${month}-${day}`;
  },

  onPublish() {
    wx.navigateTo({
      url: '/pages/publish/publish'
    });
  },

  onActivityTap(e) {
    const { id } = e.currentTarget.dataset;
    wx.navigateTo({
      url: `/pages/activity/detail?id=${id}`
    });
  },
});